import axios from "axios";
import { MessageBox, Message } from "element-ui";


//axios系统配置
const service = axios.create({
  baseURL: "http://localhost:8088",
  timeout: 5000
});

//请求拦截器
service.interceptors.request.use(
  config => {
    if (localStorage.getItem("token")) {
      config.headers["Authorization"] = localStorage.getItem("token");
    }
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  //正常xiangy
  response => {
    const res = response.data;
    if (res.code === 200) {
      Message({
        message: res.msg,
        type: "success",
        duration: 1 * 1000
      });
    } else if (res.code === 401) {
      Message({
        message: res.msg,
        type: "error",
        duration: 3 * 1000 //弹窗显示3s
      });
       localStorage.removeItem("token");
       localStorage.removeItem("userdata");
       localStorage.removeItem("userInfo");
       //上面的代码 清掉以后，必须发起一次url的改变，才会进入到 路由拦截器中
       setTimeout(1000);
       location.href = "/";
    } else if (res.code === 500) {
      MessageBox.confirm(res.msg, "数据错误", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {});
    }
    return res;
  },
  //报错
  error => {
    const res = error.response;
    if (res.status === 403) {
      Message({
        message: res.data.msg,
        type: "error",
        duration: 3 * 1000 //弹窗显示3s
      });
    }else if(err.status==401){
      Message({
        message:err.data.msg,
        type: 'error',
        duration:3*1000  //弹窗显示3s
      })
       localStorage.removeItem("token");
       localStorage.removeItem("userdata");
       localStorage.removeItem("userInfo");
       //上面的代码 清掉以后，必须发起一次url的改变，才会进入到 路由拦截器中
       setTimeout(1000);
       location.href = "/";
    } else {
      MessageBox.confirm("出错", "服务器出错", {
        confirmButtonText: "好的",
        cancelButtonText: "不要",
        type: "warning"
      })
        .then(() => {})
        .catch(() => {});
    }
  }
);

export default service;
